import md5 from "js-md5";
import qs from "qs";
import axios from "axios";
import {Toast} from 'vant';
import wx from 'weixin-js-sdk'
//对象转数组并倒序
function reverse(arys) {
  var newkey = Object.keys(arys).sort().reverse();
  var newObj = {};
  for (var i = 0; i < newkey.length; i++) {
    newObj[newkey[i]] = arys[newkey[i]];
  }
  return newObj;
}
//数组转字符串完成加密
function encryption(arys) {
  var extra_str = "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
  var jsonstr = JSON.stringify(reverse(arys));
  var str1 = jsonstr.replace(new RegExp(":", "g"), "=");
  var str2 = str1.replace(new RegExp(",", "g"), "&");
  var str3 = str2.substring(1, str2.length - 1) + extra_str;
  var _token = str3.replace(/\"/g, "");
  return _token;
}

function EncryptedCharacter(arys) {
  var param = reverse(arys);
  var extra_str = "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
  if (Object.prototype.toString.call(param) !== '[object Object]') {
    return '';
  }
  let queryParam = '';
  for (let key in param) {
    if (param.hasOwnProperty(key)) {
      let value = param[key];
      queryParam += toQueryPair(key, value);
    }
  }


  return queryParam.slice(1) + extra_str;
}

function encryption2(params, url) {
  const promise = new Promise(function (resolve, reject) {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    if (params.userId) {
      params.userId = params.userId;
    } else {
      params.userId = window.user_id;
    }
    if (params.token) {
      params.token = params.token;
    } else {
      params.token = window.userToken;
    }
    params.time = timestamp;
    // params.token = window.userToken;
    let _token = EncryptedCharacter(params);
    params.sign = md5(_token);
    axios.post(url, qs.stringify(params))
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err)
      });
  });
  return promise
}
//数组转字符串完成加密
function toQueryPair(key, value) {
  if (typeof value == 'undefined') {
    return `&${key}=`;
  }
  return `&${key}=${value}`;
}
//储存Cookie
function setCookie(cname, cvalue, exdays) {
  let date = new Date();
  date.setTime(date.getTime() + exdays * 24 * 60 * 60 * 1000);
  let expires = "expires=" + date.toGMTString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

//获取Cookie
function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
//删除指定cookie
function removeCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  var cookieStr = "";
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(name) == 0) {
      document.cookie = c + ';expires=' + new Date(0).toUTCString()
    } else {
      cookieStr += c;
      cookieStr += ";";
    }
    document.cookie = cookieStr;

  }

}
//校验手机号码
function isPhone(val) {
  var patrn = /^(((1[3456789][0-9]{1})|(15[0-9]{1}))+\d{8})$/
  if (!patrn.test(val) || val === '') {
    return false
  } else {
    return true
  }
}
//校验中英文姓名
function isName(name) {
  return /[a-zA-Z\u4E00-\u9FA5]+$/.test(name)
}
//校验输入金额
function isMoney(n) {
  return /^\d+$/.test(n)
}

//去空格
function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, '')
}


//json转url参数
function parseParam(param, key) {
  var paramStr = "";
  if (typeof (param) == 'string' || typeof (param) == 'number' || typeof (param) == 'boolean') {
    return "&" + key + "=" + encodeURIComponent(param);
  } else {
    var data = null;
    if (key) {
      data = param ? param[key] : ""
    } else {
      data = param
    }
    for (var keyTemp in data) {
      var dataTemp = data[keyTemp];
      paramStr += parseParam(dataTemp, keyTemp);
    }
  }
  return paramStr;
};

function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
  let prefix = isPrefix ? '?' : ''
  let _result = []
  if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets';
  for (let key in data) {
    let value = data[key]
    // 去掉为空的参数
    if (['', undefined, null].indexOf(value) >= 0) {
      continue;
    }
    // 如果值为数组，另行处理
    if (value.constructor === Array) {
      // e.g. {ids: [1, 2, 3]}
      switch (arrayFormat) {
        case 'indices':
          // 结果: ids[0]=1&ids[1]=2&ids[2]=3
          for (let i = 0; i < value.length; i++) {
            _result.push(key + '[' + i + ']=' + value[i])
          }
          break;
        case 'brackets':
          // 结果: ids[]=1&ids[]=2&ids[]=3
          value.forEach(_value => {
            _result.push(key + '[]=' + _value)
          })
          break;
        case 'repeat':
          // 结果: ids=1&ids=2&ids=3
          value.forEach(_value => {
            _result.push(key + '=' + _value)
          })
          break;
        case 'comma':
          // 结果: ids=1,2,3
          let commaStr = "";
          value.forEach(_value => {
            commaStr += (commaStr ? "," : "") + _value;
          })
          _result.push(key + '=' + commaStr)
          break;
        default:
          value.forEach(_value => {
            _result.push(key + '[]=' + _value)
          })
      }
    } else {
      _result.push(key + '=' + value)
    }
  }
  return _result.length ? prefix + _result.join('&') : ''
};

function backAciton() {
  var ua = navigator.userAgent.toLowerCase(); //微信小程序 
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    wx.miniProgram.navigateBack({
      delta: 1
    })
  } else {
    if (window.isiOS) {
      // console.log("iOS返回事件");
      window.webkit.messageHandlers.backAction.postMessage({});
    } else {
      // console.log("安卓返回事件");
      app.backAction();
    }
  }
};
   //点击头像进入个人主页
  function open_usrt(user) {
    if (window.isWeixin) {
      wx.miniProgram.navigateTo({
        url: "/pages/me/me?memberId=" + user,
      });
    } else {
      if (window.isiOS) {
        console.log("isiOS环境");
        window.webkit.messageHandlers.openProfile.postMessage({
          userId: user,
        });
      } else {
        console.log("安卓环境");
        app.openProfile(user);
      }
    }
  }
export default {
  open_usrt,//跳转个人主页
  parseParam,
  queryParams,
  //md5加密
  md5,
  //qs数据转换
  qs,
  //加密token  z-A
  encryption,
  //储存Cookie
  encryption2,
  //匹配文件后缀名
  setCookie,
  //获取Cookie
  getCookie,
  //校验手机号码
  isPhone,
  //校验中英文姓名
  isName,
  //校验输入金额
  isMoney,
  //去空格
  trim,
  //删除指定cookie
  removeCookie,
  //返回上一页 兼容小程序安卓ios
  backAciton
}